//
//  PVDDetailChecklistTableViewCell
//  ezyform
//
//  Created by MoennigQ on 13/4/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
class PVDDetailChecklistTableViewCell: UITableViewCell {
    
    let shadowBackView = CustomBackView()
    lazy var backView: UIView = {
        let view = UIView()
        return view
    }()
    lazy var typeImageView: UIImageView = {
        return UIImageView()
    }()
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "SFProText-Regular", size: 15)
        label.textColor = UIColor(hexStr: "#252224")
        label.numberOfLines = 2
        return label
    }()
    
    lazy var resultLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont(name: "SFProText-Regular", size: 13)
        label.textColor = UIColor(hexStr: "#00D8A0")
        label.numberOfLines = 0
        return label
    }()
    lazy var lockImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "installation_detail_checklist_lock"))
    }()
    lazy var moreImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "more_gray_icon"))
    }()
    
    lazy var booleanCheckBoxImageView: UIImageView = {
        return UIImageView()
    }()
    lazy var isRequiredImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "checkListCellStar"))
    }()
    lazy var localDataFlagImageView: UIImageView = {
        return UIImageView(image: UIImage(named: "uploadImageFailed"))
    }()
    
    lazy var bottomLineView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexStr: "#DCDCDC",alpha: 0.5)
        return view
    }()
    var booleanCheckBoxImageViewWidthConstant: Constraint?
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUpviews()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }
    func setUpviews(){
        
        self.contentView.backgroundColor = APPConfig.PVDDetailBackColor
        
        //shadowBackView,section的最后一行下边框的阴影
        self.contentView.addSubview(shadowBackView)
        shadowBackView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(20)
            make.bottom.equalToSuperview()
        }
        //
        backView.backgroundColor = .white
        self.contentView.addSubview(backView)
        backView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(56)
            make.top.bottom.equalToSuperview()
        }
        //type image view
        backView.addSubview(typeImageView)
        typeImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
        }
        //local image
        backView.addSubview(localDataFlagImageView)
        localDataFlagImageView.snp.makeConstraints { make in
            make.left.equalTo(typeImageView.snp.right).offset(-8)
            make.bottom.equalTo(typeImageView.snp.bottom).offset(3)
            make.width.height.equalTo(13)
        }
        //title label
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(typeImageView.snp.right).offset(15)
            make.top.equalToSuperview().offset(10)
            make.height.greaterThanOrEqualTo(30)
            make.width.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview().offset(-10)

        }
        //is required image
        backView.addSubview(isRequiredImageView)
        isRequiredImageView.snp.makeConstraints { make in
            make.right.equalTo(titleLabel.snp.left).offset(-3)
            make.centerY.equalToSuperview().offset(-3)
            make.width.height.equalTo(7)
        }
        //more image view
        moreImageView.contentMode = .center
        backView.addSubview(moreImageView)
        moreImageView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-12)
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
        }
        //
        backView.addSubview(booleanCheckBoxImageView)
        booleanCheckBoxImageView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(22)
            self.booleanCheckBoxImageViewWidthConstant = make.width.equalTo(0).constraint
            make.centerY.equalToSuperview()
        }
        //result label
        //抗压缩,抗拉伸能力最强，不会被压缩或拉伸
        resultLabel.setContentHuggingPriority(.required, for: NSLayoutConstraint.Axis.horizontal)
        resultLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        backView.addSubview(resultLabel)
        resultLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(5)
            make.right.equalTo(moreImageView.snp.left)
            make.height.equalTo(40)
            make.width.greaterThanOrEqualTo(24)
            make.centerY.equalToSuperview()
        }
        //bottom line
        backView.addSubview(bottomLineView)
        bottomLineView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.height.equalTo(1)
        }
        //lockImageView
        backView.addSubview(lockImageView)
        lockImageView.snp.makeConstraints { make in
            make.right.equalTo(moreImageView.snp.left)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }
        bottomLineView.isHidden = true
        isRequiredImageView.isHidden = true
        localDataFlagImageView.isHidden = true
        booleanCheckBoxImageView.isHidden = true
        lockImageView.isHidden = true
    }
    
    func setDERInfo(_ model: PVDDetailModel){
        self.isRequiredImageView.isHidden = true//是否必填项的*号标识不显示
        self.localDataFlagImageView.isHidden = true//本地数据的标识不显示
        self.titleLabel.text = "DER Register"
        if let jobStatus = model.job_status, jobStatus == "0" {
            self.typeImageView.image = UIImage(named: "installation_detail_checklist_der_disabled")
        }else{
            self.typeImageView.image = UIImage(named: "installation_detail_checklist_der")

        }
        
        self.booleanCheckBoxImageView.image = nil//bool类型的checkbox不显示
        self.booleanCheckBoxImageViewWidthConstant?.update(offset: 0)
        self.resultLabel.isHidden = true//右边的显示image数量的文本不显示
    }
    func setPanelInstalled(_ model: PVDDetailModel){
        self.typeImageView.image = UIImage(named: "installation_detail_checklist_panelinstalled")
        self.titleLabel.text = "Panel Installed"
        
        self.resultLabel.isHidden = false
        self.moreImageView.isHidden = true
        self.booleanCheckBoxImageViewWidthConstant?.update(offset: 22)
        self.booleanCheckBoxImageView.isHidden = false
        self.isRequiredImageView.isHidden = false
        if let spvInstalled = model.spv_installed, spvInstalled {
            self.resultLabel.text = ""
            self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check_sel")
        }else{
            self.resultLabel.text = "You need to be on site"
            self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check")
        }
    }
    func setData(_ model: PVDDetailModel,index: Int)
    {
        guard index < model.pvd_checklists.count else {return}//防止越界
        
        self.lockImageView.isHidden = true
        let serverModel = model.pvd_checklists[index]
        let type = serverModel.type ?? ""
        //1.当前section是否是最后
        var haveNextRowFlag: Bool = false//是否有下一行，默认没有
        if index < model.pvd_checklists.count - 1 {
            let nextRowModel = model.pvd_checklists[index + 1]
            if nextRowModel.section == serverModel.section {
                haveNextRowFlag = true
            }
        }
        if haveNextRowFlag{//有下一行
            self.backView.drawCorner(byRoundingCorners: [])
            self.shadowBackView.isHidden = true
            self.bottomLineView.isHidden = false
        }else{//没有下一行
            self.backView.drawCorner(byRoundingCorners: [.bottomLeft,.bottomRight])
            self.bottomLineView.isHidden = true
            self.shadowBackView.isHidden = false
            self.shadowBackView.drawCorner(byRoundingCorners: [.bottomLeft,.bottomRight])
            
        }
        
        if type == ChecklistType.DerRegister.rawValue{//set register
            self.setDERInfo(model)
            return
        }
        self.localDataFlagImageView.isHidden = true
        //如果开启了SPV，第一条数据要用户Panel Installed检查
        if type == ChecklistType.PanelInstalled.rawValue{
            self.setPanelInstalled(model)
            return
        }
        
        let localCheckList = model.localChecklists
        self.moreImageView.isHidden = false
        self.booleanCheckBoxImageView.isHidden = true
        self.typeImageView.image = UIImage(named:"service_bidjob_checklist_" + type + "_enabled")
        self.titleLabel.text = serverModel.title
        
        //1.boolean data have not more info
        //2.check if checklist is requird or optional
        if serverModel.is_required != nil && serverModel.is_required == "true" {
            self.isRequiredImageView.isHidden = false
        }else {
            self.isRequiredImageView.isHidden = true
        }
        //3.check if checklist is operated.(3 will cover 2 )
        switch serverModel.type! {
        case ChecklistType.Image.rawValue:
            if let jobStatus = model.job_status, jobStatus == "0"{
                self.moreImageView.isHidden = true
            }else{
                self.moreImageView.isHidden = false
            }
            self.booleanCheckBoxImageView.image = nil
            self.booleanCheckBoxImageViewWidthConstant?.update(offset: 0)
            self.resultLabel.isHidden = false
            var localAddedImagesCount: Int = 0
            var localDelImagesCount: Int = 0
            if localCheckList.count > 0 {
                //1.add images
                for localModel in localCheckList {
                    if localModel.id == serverModel.id {
                        var localAddImages = localModel.localAddImages
                        //去除本地图片和server上重复的图片(主要是处理：1.从checklist image list中返回时取消了操作队列，可能存在已经上传但网络回调没有回来的情况。2.Reupload的过程中的取消操作)
                        for serverImage in serverModel.images {
                            for i in 0..<localAddImages.count {
                                let localImage = localAddImages[i]
                                if localImage.record_at == serverImage.record_at {
                                    localAddImages.remove(at: i)
                                    break
                                }
                            }
                        }
                        localAddedImagesCount = localAddImages.count
                    }
                }
                //2.delete images from server
                for localModel in localCheckList {
                    if localModel.id == serverModel.id {
                        let localDelImages = localModel.localDeletedImages
                        localDelImagesCount = localDelImages.count
                    }
                }
            }
            //check if show local data tip image view
            if localAddedImagesCount + localDelImagesCount > 0 {
                self.localDataFlagImageView.isHidden = false
            }
            
            self.moreImageView.image = UIImage(named: "more_gray_icon")
            let imageCnt: Int = serverModel.images.count + localAddedImagesCount - localDelImagesCount
            if let spvCheck = model.spv_check, spvCheck && serverModel.id == ChecklistFixedId.certificateOfElectricalSafety.rawValue{//spv job且当前checklist是certificateOfElectricalSafety
                if imageCnt > 0 {
                    if let minImageCount = serverModel.minimum_quantity,minImageCount > 0{//只有设置了最小image cnt的才显示这样的格式
                        self.setMinImagesCount(imageCnt, minImageCount: minImageCount)
                        
                    }else{
                        self.resultLabel.text = "#\(imageCnt)"
                        self.resultLabel.textColor = UIColor(hexStr: "#00D8A0")
                    }
                }else{
                    if let minImageCount = serverModel.minimum_quantity,minImageCount > 0{
                        self.setMinImagesCount(0, minImageCount: minImageCount)
                    }else{
                        self.resultLabel.text = ""
                    }
                }
            }else{
                if imageCnt > 0 {
                    if let minImageCount = serverModel.minimum_quantity,minImageCount > 0{//只有设置了最小image cnt的才显示这样的格式
                        self.setMinImagesCount(imageCnt, minImageCount: minImageCount)
                        
                    }else{
                        self.resultLabel.text = "#\(imageCnt)"
                        self.resultLabel.textColor = UIColor(hexStr: "#00D8A0")
                    }
                }else{
                    if let minImageCount = serverModel.minimum_quantity,minImageCount > 0{
                        self.setMinImagesCount(0, minImageCount: minImageCount)
                    }else{
                        self.resultLabel.text = ""
                    }
                }
            }
            
            
        case ChecklistType.Text.rawValue:
            if let jobStatus = model.job_status, jobStatus == "0"{
                self.moreImageView.isHidden = true
            }else{
                self.moreImageView.isHidden = false
            }
            self.booleanCheckBoxImageView.image = nil
            self.booleanCheckBoxImageViewWidthConstant?.update(offset: 0)
            self.resultLabel.isHidden = false
            self.resultLabel.text = ""
            var localFlag: Bool = false
            if localCheckList.count > 0 {//check local data
                for localModel in localCheckList {
                    if localModel.id == serverModel.id {
                        self.localDataFlagImageView.isHidden = false
                        localFlag = true
                        serverModel.answer = localModel.answer
                        if localModel.answer != "" {
                            self.resultLabel.text = NSLocalizedString("pvd.detail.status.done", comment: "")

                        }
                        
                    }
                }
            }
            if !localFlag  {
                if serverModel.answer != nil && serverModel.answer != "" {
                    self.resultLabel.text = NSLocalizedString("pvd.detail.status.done", comment: "")
                }
            }
        case ChecklistType.Bool.rawValue:
            self.moreImageView.isHidden = true
            self.booleanCheckBoxImageView.isHidden = false
            self.booleanCheckBoxImageViewWidthConstant?.update(offset: 22)
            self.resultLabel.isHidden = true
            var localFlag: Bool = false
            //1.check if local data exist
            if localCheckList.count > 0 {
                for localModel in localCheckList {
                    if localModel.id == serverModel.id{
                        self.localDataFlagImageView.isHidden = false
                        localFlag = true
                        if localModel.answer == "true" {
                            self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check_sel")
                            
                        }else{
                            self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check")
                        }
                        
                    }
                }
            }
            //2.use server data if local data not exist
            if !localFlag {
                if serverModel.answer != nil && serverModel.answer == "true" {
                    self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check_sel")
                }else{
                    self.booleanCheckBoxImageView.image = UIImage(named: "PVDDetail_checklist_btn_check")
                }
            }
        default:
            break
        }
        
    }
    
    func setMinImagesCount(_ imageCnt: Int, minImageCount: Int64){
        let subStr = "\(imageCnt)"
        let content = subStr + "/\(minImageCount)"
        let attrString = NSMutableAttributedString(string: content )
        let attr1: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(red: 0.64, green: 0.64, blue: 0.64,alpha:1)]
        let attr2: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(red: 0, green: 0.85, blue: 0.63,alpha:1)]
        
        attrString.addAttributes(attr1, range: NSRange(location: 0, length: attrString.length))
        attrString.addAttributes(attr2, range: NSRange(location: 0, length: subStr.count))
        self.resultLabel.attributedText = attrString
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}
